package com.tqw.client.service.impl;

import com.tqw.client.dao.ClientMapper;
import com.tqw.client.pojo.ClientPassword;
import com.tqw.client.service.ClientService;
import com.tqw.entity.JWTUtil;
import com.tqw.pojo.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


/**
 * @author Will
 */
@Service
public class ClientServiceImpl implements ClientService {

    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 需求: 查询用户 通过id
     * @param
     * @return Client
     */
    @Override
    public Client selectUserById(Integer clientId) {
        Client client = clientMapper.selectById(clientId);
        return client;
    }

    /**
     * 需求: 修改个人信息 通过from表单
     * @param client
     * @return Client
     */
    @Override
    public Client updateInformation(Client client) {
        clientMapper.updateById(client);
        return client;
    }

    /**
     * 需求: 检查输入的原密码是否正确
     * @param password
     * @return Client
     */
    @Override
    public Boolean checkPassword(String password,String token) {
        Integer id = JWTUtil.getId(token);
        String s = clientMapper.findPassword(id);
        return passwordEncoder.matches(password, s);
    }

    /**
     * 需求: 比对（输入新密码）和（再次输入新密码）
     * 参数：String newPassword ， String newPasswordAgain
     * @return boolean
     */
    @Override
    public Boolean contrastPassword(ClientPassword clientPassword) {
        return clientPassword.getNewPassword() != null && clientPassword.getNewPasswordAgain() != null
                && !"".equals(clientPassword.getNewPassword()) && !"".equals(clientPassword.getNewPasswordAgain())
                && clientPassword.getNewPassword().equals(clientPassword.getNewPasswordAgain());
    }


    /**
     * 需求: 修改密码
     * @param clientPassword
     * @return boolean
     */
    @Override
    public Boolean updatePassword(ClientPassword clientPassword,String token) {
        Integer id = JWTUtil.getId(token);
        if(this.checkPassword(clientPassword.getOldPassword(), token)){
            clientMapper.updatePassword(passwordEncoder.encode(clientPassword.getNewPassword()),id);
            return true;
        }
        return false;
    }
}
